package net.yla.smartbus.module.ba.SendSMS.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;
import net.yla.smartbus.core.api.RequestCode;
import net.yla.smartbus.core.base.BaseService;
import net.yla.smartbus.core.exception.AppException;
import net.yla.smartbus.core.util.SixNum;
import net.yla.smartbus.module.ba.SendSMS.constant.aliConstant;
import net.yla.smartbus.module.ba.SendSMS.service.RedisService;
import net.yla.smartbus.module.ba.SendSMS.service.SendSMSService;
import net.yla.smartbus.module.ba.smsMessages.form.SmsMessagesForm;
import net.yla.smartbus.module.ba.smsMessages.mapper.SmsMessagesDOMapper;
import net.yla.smartbus.module.ba.smsMessages.query.SmsMessagesQuery;
import net.yla.smartbus.module.ba.smsMessages.serivce.SmsMessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:LiuJie
 * @date:2020/8/17
 * @description:发送短信验证码
 */
@Service
public class SendSMSServiceImpl extends BaseService implements SendSMSService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private SmsMessagesService smsMessagesService;
    @Autowired
    private SmsMessagesDOMapper smsMessagesDOMapper;


    /**
     * 发送验证码
     *
     * @param moblie 手机号
     * @return
     */
    @Override
    public int sendSms(String moblie) {
        //要发送的验证码
        String idCode;
        //1. 判断是否缓存该账号验证码
        String returnCode = redisService.get(moblie + aliConstant.smsLoginID);

        if (returnCode != null) {
            // 如果returnCode存在直接使用
            idCode = returnCode;
        } else {
            // 生成6位短信验证码
            idCode = SixNum.getSixNum();
        }
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("code", idCode);

        // 发送短信
        DefaultProfile profile = DefaultProfile.getProfile("default", aliConstant.accessKeyId, aliConstant.accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(aliConstant.accessKeyDoMain);
        request.setVersion("2017-05-25");
        // 发送短信接口名
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", moblie);
        // 短信签名名称 申请完成短信签名
        request.putQueryParameter("SignName", "逸路安科技股份有限公司");
        // 模板ID 短信模板创建完成后，会自带模板ID，阿里短信平台控制台
        request.putQueryParameter("TemplateCode", "SMS_178980466");
        // 短信模板中的变量参数
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + idCode + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject object = JSON.parseObject(response.getData());

            //短信发送成功后存入redis
            if (response != null && aliConstant.smsOK.equalsIgnoreCase((String) object.get("Message"))
                    && com.aliyuncs.utils.StringUtils.isEmpty(returnCode)) {
                // code单位秒  30秒
                redisService.set(moblie + aliConstant.smsLoginID, idCode, 30);

                String s = redisService.get(moblie + aliConstant.smsLoginID);
                //发送成功后存入短信发送日志
                SmsMessagesForm form = new SmsMessagesForm();
                form.setTo(moblie);
                form.setFrom("12345678996");
                form.setIp(19216801);
                form.setCount(1);
                form.setMessage(idCode);
                form.setMessageType(1);
                form.setState(1);
                form.setSmsPlatform(1);
                int i = smsMessagesService.addForm(form);
                System.out.println(s);

            }
            return RequestCode.success;

        } catch (ServerException e) {
            throw new AppException("未知错误", RequestCode.server_error);
        } catch (ClientException e) {
            throw new AppException("未知错误", RequestCode.server_error);
        }
    }

    /**
     * 验证用户验证码
     *
     * @param moblie 手机号
     * @param code   验证码
     * @return
     */
    @Override
    public int checkSms(String moblie, String code) {
        if (com.aliyuncs.utils.StringUtils.isEmpty(moblie)) {
            throw new AppException("手机号码为空", 10003);
        }

        if (com.aliyuncs.utils.StringUtils.isEmpty(code)) {

            throw new AppException("验证码为空", 10004);
        }

        try {
            String returnCode = redisService.get(moblie + aliConstant.smsLoginID);
            //String returnCode = "123456";
            if (!StringUtils.isEmpty(returnCode) && returnCode.equals(code)) {

                // 验证成功, 删除redis.
                redisService.del(moblie + aliConstant.smsLoginID);
                return 200;
            }
            // 验证失败，返回非200
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException("验证码错误", 10005);
        }
    }
    
}
